package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.system.dtos.request.SysResourceRoleResp;
import com.rightsidetech.system.dtos.request.SysRoleAddReq;
import com.rightsidetech.system.dtos.request.SysRoleReq;
import com.rightsidetech.system.dtos.request.SysRoleUpdateReq;
import com.rightsidetech.system.dtos.response.SysRoleDetailResp;
import com.rightsidetech.system.dtos.response.SysRoleResp;
import com.rightsidetech.system.dtos.response.SysRoleSelectResp;
import com.rightsidetech.system.entity.*;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-10-20 09:13
 */
@Slf4j
@Service("SysRoleServiceImpl")
public class SysRoleServiceImpl implements SysRoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleResourceMapper sysRoleResourceMapper;
    @Resource
    private SysResourceMapper sysResourceMapper;
    @Resource
    private SysRoleAccountMapper sysRoleAccountMapper;
    @Resource
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;

    @Resource
    private SysAgentLoginInfoMapper sysAgentLoginInfoMapper;
    @Resource
    private SysAgentRoleMapper sysAgentRoleMapper;
    @Resource
    private SysAgentResourceMapper sysAgentResourceMapper;
    @Resource
    private SysAgentRoleAccountMapper sysAgentRoleAccountMapper;
    @Resource
    private SysAgentRoleResourceMapper sysAgentRoleResourceMapper;
    @Resource
    private SysUserInfoMapper sysUserInfoMapper;

    @Override
    public ResponseData<PageInfo<SysRoleResp>> page(SysRoleReq sysRoleReq) throws Exception {
        PageHelper.startPage(sysRoleReq.getPageNo(), sysRoleReq.getPageSize());
        List<SysRoleResp> list = sysRoleMapper.selectList(sysRoleReq);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData saveSysRole(SysRoleAddReq sysRoleAddReq, Long loginInfoId) throws Exception {
        SysRole sysRole = new SysRole();
        sysRole.setName(sysRoleAddReq.getName());
        sysRole.setRoleDetail(sysRoleAddReq.getRoleDetail());
        sysRole.setCreaterId(loginInfoId);
        sysRole.setCreatedAt(new Date());
        //判断角色名称是否重复
        SysRole ucSysRole1 = sysRoleMapper.selectByName(sysRole.getName());
        if (null != ucSysRole1) {
            return ResponseData.fail("角色名称重复");
        }
        sysRoleMapper.insertSelective(sysRole);
        //添加权限
        roleAddResource(sysRole.getId(), sysRoleAddReq.getResourceList());
        return ResponseData.success();
    }

    private void roleAddResource(Long roleId, List<Long> resourceList) {
        //添加权限
        List<SysRoleResource> list = new ArrayList<>();
        resourceList.forEach(item -> {
            SysRoleResource sysRoleResource = new SysRoleResource();
            sysRoleResource.setRoleId(roleId);
            sysRoleResource.setResourceId(item);
            sysRoleResource.setCreatedAt(new Date());
            list.add(sysRoleResource);

        });
        sysRoleResourceMapper.insertRoleResouceList(list);

    }

    @Override
    public ResponseData updateSysRole(SysRoleUpdateReq sysRoleUpdateReq, Long loginInfoId) throws Exception {
        //判断角色是否已经删除
        SysRole sysRole2 = sysRoleMapper.selectByPrimaryKey(sysRoleUpdateReq.getId());
        if (ObjectUtils.isEmpty(sysRole2)) {
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        SysRole sysRole1 = sysRoleMapper.selectByName(sysRoleUpdateReq.getName());
        if (null != sysRole1 && !sysRoleUpdateReq.getId().equals(sysRole1.getId())) {
            return ResponseData.fail("角色名称重复");
        }
        SysRole sysRole = new SysRole();
        sysRole.setId(sysRoleUpdateReq.getId());
        sysRole.setName(sysRoleUpdateReq.getName());
        sysRole.setRoleDetail(sysRoleUpdateReq.getRoleDetail());
        sysRole.setUpdatedAt(new Date());
        sysRole.setUpdaterId(loginInfoId);

        sysRoleMapper.updateByPrimaryKeySelective(sysRole);

        //删除之前权限
        sysRoleResourceMapper.delByRoleId(sysRoleUpdateReq.getId());
        //添加权限
        List<SysRoleResource> sysRoleResourceList = new ArrayList<>();
        for (Long resourceId : sysRoleUpdateReq.getResourceList()) {
            SysRoleResource sysRoleResource = new SysRoleResource();
            sysRoleResource.setResourceId(resourceId);
            sysRoleResource.setRoleId(sysRoleUpdateReq.getId());
            sysRoleResource.setCreatedAt(new Date());
            sysRoleResourceList.add(sysRoleResource);
        }
        sysRoleResourceMapper.insertRoleResouceList(sysRoleResourceList);

        return ResponseData.success();
    }

    @Override
    public ResponseData delSysRole(DelReq delReq) throws Exception {
        //关联帐号不能删除
        int i = sysRoleAccountMapper.selectByRoleId(delReq.getId());
        if (i > 0) {
            return ResponseData.fail("此角色已关联帐号");
        }
        SysRole sysRole = new SysRole();
        sysRole.setId(delReq.getId());
        sysRole.setIsDeleted((byte) 1);
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        return ResponseData.success();
    }

    @Override
    public ResponseData selectList() throws Exception {
        List<SysRoleSelectResp> list = sysRoleMapper.selectChooseList();
        return ResponseData.success(list);
    }

    @Override
    public ResponseData<SysRoleDetailResp> getRoleDetail(Long roleId) throws Exception {
        SysRoleDetailResp sysRoleDetailResp = sysRoleMapper.selectByRoleId(roleId);
        return ResponseData.success(sysRoleDetailResp);
    }

    @Override
    public ResponseData getResources(Long roleId) throws Exception {
        List<SysResource> list = null;
        if (!StringUtil.isNullorEmpty(roleId)) {
            list = sysResourceMapper.selectRoleResourceList(roleId);
        }

        List<SysResourceRoleResp> allList = sysResourceMapper.selectAllResource();

        if (null != list && list.size() > 0 && null != allList && allList.size() > 0) {
            for (SysResourceRoleResp roleResp : allList) {
                boolean show = false;
                for (SysResource sysResource : list) {
                    if (sysResource.getId().equals(roleResp.getId())) {
                        show = true;
                    }
                }
                if (show) {
                    roleResp.setShow(1);
                }
            }
        }
        return ResponseData.success(allList);
    }

    @Override
    public ResponseData bindRoles(String loginName, String roleName, String pwd) throws Exception {
        SysUserLoginInfo sysUserLoginInfo = sysUserLoginInfoMapper.selectByLoginName(loginName);
        if (StringUtils.isEmpty(sysUserLoginInfo)) {
            //添加帐号
            sysUserLoginInfo = new SysUserLoginInfo();
            sysUserLoginInfo.setLoginName(loginName);
            sysUserLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
            sysUserLoginInfo.setPassword(DigestUtils.md5DigestAsHex((pwd + sysUserLoginInfo.getSalt()).getBytes()));

            sysUserLoginInfoMapper.insertSelective(sysUserLoginInfo);

            SysUserInfo sysUserInfo = new SysUserInfo();
            sysUserInfo.setLoginInfoId(sysUserLoginInfo.getId());
            sysUserInfo.setConnectWay(loginName);
            sysUserInfo.setCreaterId(sysUserLoginInfo.getId());
            sysUserInfo.setCreatedAt(new Date());
            sysUserInfo.setName(loginName);
            sysUserInfoMapper.insertSelective(sysUserInfo);
        }else{
            SysUserLoginInfo sysUserLoginInfo2 = new SysUserLoginInfo();
            sysUserLoginInfo2.setId(sysUserLoginInfo.getId());
            sysUserLoginInfo2.setSalt(String.valueOf(Math.random() * 900000 + 100000));
            sysUserLoginInfo2.setPassword(DigestUtils.md5DigestAsHex((pwd + sysUserLoginInfo2.getSalt()).getBytes()));
            sysUserLoginInfoMapper.updateByPrimaryKeySelective(sysUserLoginInfo2);
        }
        List<Long> longs = sysResourceMapper.selectAllId();
        SysRoleAddReq sysRoleAddReq = new SysRoleAddReq();
        sysRoleAddReq.setName(roleName);
        sysRoleAddReq.setRoleDetail("绑定所有菜单权限角色");
        sysRoleAddReq.setResourceList(longs);
        ResponseData responseData = saveSysRole(sysRoleAddReq, sysUserLoginInfo.getId());
        if (responseData.getCodeId() != 1) {
            return responseData;
        }
        //更新roleId
        SysRoleAccount sysRoleAccount = sysRoleAccountMapper.selectByloginInfoId(sysUserLoginInfo.getId());
        SysRole sysRole = sysRoleMapper.selectByName(roleName);
        if (StringUtils.isEmpty(sysRole)) {
            return ResponseData.fail("角色未添加成功");
        }
        if (!StringUtils.isEmpty(sysRoleAccount)) {
            Long id = sysRoleAccount.getId();
            sysRoleAccount = new SysRoleAccount();
            sysRoleAccount.setId(id);
            sysRoleAccount.setRoleId(sysRole.getId());
            sysRoleAccount.setUpdatedAt(new Date());
            sysRoleAccountMapper.updateByPrimaryKeySelective(sysRoleAccount);
        } else {
            SysRoleAccount roleAccount = new SysRoleAccount();
            roleAccount.setLoginInfoId(sysUserLoginInfo.getId());
            roleAccount.setRoleId(sysRole.getId());
            roleAccount.setCreatedAt(new Date());
            sysRoleAccountMapper.insertSelective(roleAccount);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData<Boolean> checkAuth(Long loginInfoId, String biz, String requestURI, String menuUrl) {
        try {
            Boolean result = true;
            //运营端
            if ("OPERATOR".equals(biz)){
                SysUserLoginInfo sysUserLoginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(loginInfoId);
                if (sysUserLoginInfo == null){
                    return ResponseData.success(false);
                }
                //根据账户id查询角色id
                SysRoleAccount sysRoleAccount = sysRoleAccountMapper.selectByloginInfoId(loginInfoId);
                if (sysRoleAccount == null) {
                    return ResponseData.success(false);
                } else {
                    SysRole sysRole = sysRoleMapper.selectByPrimaryKey(sysRoleAccount.getRoleId());
                    if (!ObjectUtils.isEmpty(sysRole) && "超级管理员".equals(sysRole.getName())){
                        return ResponseData.success(result);
                    }
                    // 根据角色id查询资源集合
                    List<Long> resourcesIds = sysRoleResourceMapper.selectByRoleId(sysRoleAccount.getRoleId());
                    Long resourcesId = sysResourceMapper.selevtByUrl(requestURI, menuUrl);
                    if (resourcesId != null) {
                        int count = Collections.frequency(resourcesIds, resourcesId);
                        if (count <= 0) {
                            result = false;
                        }
                    }else {
                        result = false;
                    }
                    return ResponseData.success(result);
                }
            }else if ("AGENT".equals(biz)){
                SysAgentLoginInfo sysAgentLoginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
                if (sysAgentLoginInfo == null) {
                    return ResponseData.success(false);
                }
                //根据账户id查询角色id
                SysAgentRoleAccount sysAgentRoleAccount = sysAgentRoleAccountMapper.selectByLoginId(loginInfoId);
                if (sysAgentRoleAccount == null) {
                    return ResponseData.success(false);
                } else {
                    // 根据角色id查询资源集合
                    List<Long> resourcesIds = sysAgentRoleResourceMapper.selectByRoleId(sysAgentRoleAccount.getRoleId());
                    Long resourcesId = sysAgentResourceMapper.selevtByUrl(requestURI, menuUrl);
                    if (resourcesId != null) {
                        int count = Collections.frequency(resourcesIds, resourcesId);
                        if (count <= 0) {
                            result = false;
                        }
                    } else {
                        result = false;
                    }
                    return ResponseData.success(result);
                }
            }else {
                return ResponseData.success(false);
            }

        } catch (Exception e) {
            log.error("校验权限异常：",e);
            return ResponseData.success(false);
        }
    }

    @Override
    public SysRole selectById(Long id) {
        return sysRoleMapper.selectByPrimaryKey(id);
    }
}
